<?php

namespace Managers;

class PdfFile extends BaseManager
{
    const TABLE = '\Catalog\PdfFile';
    protected $__table = self::TABLE;

    public function add(array $values)
    {
        $uploadDir = \Zend_Registry::get('config')->pdf->upload->dir;
        $fileName = $this->getFileName(dirname(APPLICATION_PATH) . $uploadDir, $values['upload']);
        $entity = new \Catalog\PdfFile();
        $entity->setUrl($fileName);
        $issueRef = $this->_em->getReference(Issue::TABLE, $values['issue']);
        $entity->setIssue($issueRef);
        $entity->setIsParsed(false);
        $entity->setIsDel(false);
        $this->_em->persist($entity);
        $this->_em->flush();
        return $entity;
    }

    private function getFileName($uploadDir, $fileName)
    {
        $char = 0;
        do {
            $newFileName = pathinfo($fileName, PATHINFO_FILENAME) . $char . '.' . pathinfo($fileName, PATHINFO_EXTENSION);
            $newFilePath = $uploadDir . $newFileName;
            $char++;
        } while (file_exists($newFilePath));
        rename($uploadDir . $fileName, $newFilePath);
        return $newFileName;
    }

    /**
     * @return \Catalog\PdfFIle[]
     */
    public function getUnparsedList()
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('pf.isParsed = 0');
        $res = $qb->getQuery()->getResult();
        return $res;
    }

    public function setParsed(\Catalog\PdfFile $entity)
    {
        $entity->setIsParsed(true);
        $this->_em->persist($entity);
        $this->_em->flush();
    }

    public function getList()
    {
        $qb = $this->createQueryBuilder()
            ->addOrderBy('pf.id', 'DESC');
        $res = $qb->getQuery()->getArrayResult();
        return $res;
    }

    protected function createQueryBuilder()
    {
        $qb = parent::createQueryBuilder()
            ->select('pf, i')
            ->from($this->__table, 'pf')
            ->join('pf.issue', 'i')
            ->andWhere('pf.isDel = 0')
            ->andWhere('i.isDel = 0');
        return $qb;
    }

    public function getLast()
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('pf.isParsed = 1')
            ->orderBy('i.id', 'DESC')
            ->setMaxResults(1);
        $res = $qb->getQuery()->getArrayResult();

        return count($res) ? $res[0] : false;
    }


}
